const rawBody = require('raw-body')
const contentType = require('content-type')
const xmljs = require('xml-js')

module.exports = async (ctx) => {
  let xml = await rawBody(ctx.req, {
    length: ctx.req.headers['content-length'],
    limit: '1mb',
    encoding: contentType.parse(ctx.req).parameters.charset
  })

  let result = xmljs.xml2js(xml, {
    compact: true,
    cdataKey: 'value',
    textKey: 'value'
  }).xml;

  //归并,扁平化对象
  let newObj = Object.keys(result).reduce((obj, key) => {
    obj[key] = result[key]['value']
    return obj;
  }, {})
  console.log(newObj);
  await ctx.render('replay', {
    ToUserName: newObj.FromUserName,
    FromUserName: newObj.ToUserName,
    CreateTime: new Date().toLocaleString(),
    Content: '<a href="https://www.web678.xyz/index.html"> gp16 demo </a>'
  })
}